#!/usr/bin/env bash

# 设置工作目录为脚本所在目录，确保所有相对路径都正确
cd "$(dirname "$0")" || exit 1

# 设置日志目录和文件
LOG_DIR="logs"
mkdir -p "$LOG_DIR"
RUN_LOG_FILE="$LOG_DIR/run_collect_daemon.log"
RUN_ERROR_LOG="$LOG_DIR/run_collect_daemon_error.log"

# 定义总轮询周期为10分钟（600秒）
readonly CYCLE_INTERVAL_SECONDS=600

# 定义报告相关的锁文件路径
readonly DAILY_LOCK_FILE=".daily_report_lock"
readonly MONTHLY_LOCK_FILE=".monthly_report_lock"

# 日志函数
log_message() {
    echo "$(date '+%Y-%m-%d %H:%M:%S.%3N') - $1" >> "$RUN_LOG_FILE"
}

# 错误日志函数
log_error() {
    echo "$(date '+%Y-%m-%d %H:%M:%S.%3N') - ERROR: $1" >> "$RUN_ERROR_LOG"
}

# 检查守护进程是否存在
is_daemon_running() {
    pgrep -f "run_collect.sh run" >/dev/null
}

# 获取守护进程的PID
get_daemon_pid() {
    pgrep -f "run_collect.sh run"
}

# 检查是否应该运行日报
should_run_daily_report() {
    local current_hour; current_hour=$(date +%H)
    local today; today=$(date +%Y-%m-%d)
    if [ "$current_hour" = "23" ] && { [ ! -f "$DAILY_LOCK_FILE" ] || [ "$(cat "$DAILY_LOCK_FILE")" != "$today" ]; }; then
        return 0
    fi
    return 1
}

# 检查是否应该运行月报
should_run_monthly_report() {
    local current_day; current_day=$(date +%d)
    local current_hour; current_hour=$(date +%H)
    local last_month; last_month=$(date -d "last month" '+%Y-%m')
    if [ "$current_day" = "01" ] && [ "$current_hour" = "01" ] && { [ ! -f "$MONTHLY_LOCK_FILE" ] || [ "$(cat "$MONTHLY_LOCK_FILE")" != "$last_month" ]; }; then
        return 0
    fi
    return 1
}

# 停止进程
stop_process() {
    if ! is_daemon_running; then
        log_message "No data collection service running."
        return 0
    fi

    log_message "Stopping data collection service..."
    local pid
    pid=$(get_daemon_pid)

    if [ -z "$pid" ]; then
        log_error "Service check was positive, but could not find PID."
        return 1
    fi

    kill -15 "$pid" 2>/dev/null
    sleep 2

    if is_daemon_running; then
        log_message "Service did not stop gracefully, forcing termination (kill -9)."
        kill -9 "$pid" 2>/dev/null
        sleep 2
    fi

    if ! is_daemon_running; then
        log_message "Data collection service stopped successfully."
        return 0
    else
        log_error "Failed to stop the service with PID $pid. Manual intervention required."
        return 1
    fi
}

# 采集和调度的主循环
start_collect() {
    if [ ! -f "collect_traffic.sh" ]; then
        log_error "Core script 'collect_traffic.sh' is missing."
        exit 1
    fi
    chmod +x collect_traffic.sh get_port_traffic.exp

    log_message "Data collection and report scheduling service started in background. Target cycle interval is ${CYCLE_INTERVAL_SECONDS} seconds."

    while true; do
        if should_run_monthly_report; then
            log_message "Triggering MONTHLY report generation."
            ./collect_traffic.sh --monthly
            log_message "Monthly report generation task finished (Check its own log for details)."
            continue
        fi

        if should_run_daily_report; then
            log_message "Triggering DAILY report generation."
            ./collect_traffic.sh --daily
            log_message "Daily report generation task finished (Check its own log for details)."
            continue
        fi

        local start_time; start_time=$(date +%s)
        log_message "Collection cycle STARTED."

        if ./collect_traffic.sh; then
            : # 成功时静默，日志由子脚本记录
        else
            log_error "Collection cycle script 'collect_traffic.sh' exited with an error."
        fi

        local end_time; end_time=$(date +%s)
        local duration; duration=$((end_time - start_time))
        log_message "Collection cycle FINISHED. Duration: ${duration} seconds."

        local wait_time; wait_time=$((CYCLE_INTERVAL_SECONDS - duration))
        if [ "$wait_time" -gt 0 ]; then
            log_message "Waiting for ${wait_time} seconds. Next cycle will start around $(date -d "+${wait_time} seconds" '+%Y-%m-%d %H:%M:%S')."
            sleep "$wait_time"
        else
            log_message "WARNING: Cycle duration (${duration}s) exceeded target interval (${CYCLE_INTERVAL_SECONDS}s). Starting next cycle immediately."
            sleep 1
        fi
    done
}

# 启动服务函数
start_service() {
    if is_daemon_running; then
        echo "Error: Data collection service is already running." >&2
        show_status
        return 1
    fi

    nohup "$0" run >/dev/null 2>&1 &

    log_message "Sent start command for the data collection service."
    echo "Sent start command. Checking status in 2 seconds..."
    sleep 2

    if is_daemon_running; then
        log_message "Service started successfully."
        show_status
        return 0
    else
        log_error "Service failed to start. Check error logs: $RUN_ERROR_LOG"
        echo "Error: Service failed to start. Check logs in ${LOG_DIR}/" >&2
        return 1
    fi
}

# 重启服务函数
restart_service() {
    echo "Restarting data collection service..."
    if stop_process; then
        echo "Service stopped successfully."
    else
        echo "Warning: Could not stop the service, or it was not running. Proceeding to start." >&2
    fi

    sleep 2

    if start_service; then
        echo "Service restart command sent successfully."
        return 0
    else
        echo "Error: Failed to restart the data collection service." >&2
        return 1
    fi
}

# status命令的详细信息显示
show_status() {
    if is_daemon_running; then
        local pid
        pid=$(get_daemon_pid)
        echo "Data collection service is RUNNING with PID: $pid"
        echo "---"
        ps -f --ppid "$pid" -p "$pid"
        return 0
    else
        echo "Data collection service is STOPPED."
        return 1
    fi
}

# 主程序
case "$1" in
    start)
        start_service
        ;;
    status)
        show_status
        ;;
    stop)
        if stop_process; then echo "Data collection service stopped successfully.";
        else echo "Failed to stop service, or it was not running."; fi
        ;;
    restart)
        restart_service
        ;;
    run)
        start_collect
        ;;
    *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
        ;;
esac

exit $?